//
//  LSCupTableFixturesViewController.m
//  LookScore
//
//  Created by wr on 2018/5/23.
//  Copyright © 2018年 ChongQingXunTiCompany. All rights reserved.
//

#import "LSCupTableFixturesViewController.h"
#import "UIViewController+ZJScrollPageController.h"
#import "LSPulldDownOptionsView.h"//下拉view
#import "LSCupScheduleCell.h"
#import "LSCupIntegralModel.h"
#import "LSCupIntegralHeaderView.h"
#import "LSCupIntergralTableHeaderView.h"
#define Start_X          LSAutoVlaue(15.0f,LSScreenHeight)      // 第一个按钮的X坐标
#define Start_Y          LSAutoVlaue(46.0f,LSScreenHeight)     // 第一个按钮的Y坐标
#define Width_Space      LSAutoVlaue(30.0f,LSScreenWidth)      // 2个按钮之间的横间距
#define Height_Space     LSAutoVlaue(20.0f,LSScreenHeight)     // 竖间距
#define Button_Width     (LSScreenWidth-2*Start_X-3*Width_Space)/4    // 宽
#define Button_Height    LSAutoVlaue(30.0f,LSScreenHeight)     // 高



@interface LSCupTableFixturesViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(strong,nonatomic)UITableView *tableView;

//@property(strong,nonatomic)LSPulldDownOptionsView *pullView;
//
//@property(strong,nonatomic)UIButton *categoryBu;

@property(nonatomic,strong)NSMutableArray *intergralListArray;//杯赛积分榜数据源

@property(nonatomic,strong)NSMutableArray *kindListArray;//杯赛阶段数据源

@property(nonatomic,strong)NSMutableArray *matchListArray;//杯赛赛程数据源

//@property(assign,nonatomic)NSInteger  pageIndex;

@property (nonatomic, strong) NSMutableArray * nullMatchListArray;//无积分赛的赛程数据源
@property (nonatomic, strong) NSMutableArray * nullMatchListCopyArray;

@property (nonatomic, assign) BOOL tableOrFixture;
@property (nonatomic, assign) NSInteger selectSection;
@property (nonatomic, strong) NSArray * imageArray;
@end

@implementation LSCupTableFixturesViewController{
    UIButton *checkMoreBtn;
    UIButton *selectedBtn;
    NSInteger selectTag;
    BOOL isOpen;
    CGFloat headerHeight;
    NSInteger _intergralTag;//选择的阶段在积分数组中的位子
    
    NSString * _kindId;
    LSCupIntergralTableHeaderView * _headerView;
}
- (NSMutableArray *)nullMatchListArray{
    if (!_nullMatchListArray) {
        _nullMatchListArray = @[].mutableCopy;
    }
    return _nullMatchListArray;
}

- (NSMutableArray *)nullMatchListCopyArray{
    if (!_nullMatchListCopyArray) {
        _nullMatchListCopyArray = @[].mutableCopy;
    }
    return _nullMatchListCopyArray;
}
- (NSMutableArray *)kindListArray{
    if (!_kindListArray) {
        _kindListArray = @[].mutableCopy;
    }
    return _kindListArray;
}

- (NSMutableArray *)intergralListArray{
    if (!_intergralListArray) {
        _intergralListArray = @[].mutableCopy;
    }
    return _intergralListArray;
}

- (NSMutableArray *)matchListArray{
    if (!_matchListArray) {
        _matchListArray = @[].mutableCopy;
    }
    return _matchListArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    if (@available(iOS 11.0, *)) {
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
    }
    [self.view addSubview:self.tableView];
//    [self loadLeagueData:YES];
    [self loadData:YES];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        [self loadLeagueData:YES];
        [self loadData:YES];
    }];
    // Do any additional setup after loading the view.
    self.imageArray = @[@"GoldCup",@"SilverCup",@"CopperCup"];
    
    _headerView = [[LSCupIntergralTableHeaderView alloc] initWithFrame:CGRectMake(0, 0, LSScreenWidth, 30)];
    KWeakSelf(self);
    KWeakSelf(_headerView);
    _headerView.btnClickBlock = ^(NSInteger tag) {
        [weakself getTheCorrespondingData:tag];
    };
    _headerView.moreBtnBlock = ^{
        [weakself.tableView beginUpdates];
        weakself.tableView.tableHeaderView = weak_headerView;
        [weakself.tableView endUpdates];
        [weakself.tableView reloadData];
    };
    self.tableView.tableHeaderView = _headerView;
    
}

-(void)zj_viewDidLoadForIndex:(NSInteger)index{
//    MyLog(@"leagueType --- %ld",self.leagueType);
    
}
- (void)loadLeagueData:(BOOL)refresh{
    
    [LSHttpEnclosureTool GET:LSDataBaseCupKindList parameters:@{@"leagueId":self.leagueId,@"matchSeason":self.season} resBlock:^(id responseObject) {
//        if (responseObject) {
////            self.kindListArray = responseObject;
//            NSMutableArray * array = responseObject;
//            [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                KindListModel * model = [KindListModel mj_objectWithKeyValues:obj];
//                [self.kindListArray addObject:model];
//                if (model.IsCurrent) {
//                    selectTag = idx;
//                    _kindId = model.KindId;
//                    [self loadData:YES];
//                }
//            }];
//            [self.tableView setTableHeaderView:[self tableHeadView]];
//        }
//
    }];
    
//    MyLog(@"leagueId --- %@ /n season --- %@",self.leagueId,self.season);
    
   
}


- (void)loadData:(BOOL)refresh{
    
    [LSHttpEnclosureTool GET:LSLeagueIntergralAndMatchList parameters:@{@"leagueId":self.leagueId,@"matchSeason":self.season} resBlock:^(id responseObject) {
        MyLog(@"leagueTable ---- %@",responseObject);
        if (responseObject) {
            if (refresh) {
                [self.intergralListArray removeAllObjects];
                [self.matchListArray removeAllObjects];
                [self.kindListArray removeAllObjects];
            }
            //杯赛积分
            for (NSDictionary * dict in responseObject[@"IntergralList"]) {
                LSCupIntegralModel * model = [LSCupIntegralModel mj_objectWithKeyValues:dict];
                [self.intergralListArray addObject:model];
                
            }
            //杯赛赛事
            for (NSDictionary * dict in [self extractionOfTheSameElementWithArray:responseObject[@"MatchList"]]) {
                MatchListModel * model = [MatchListModel mj_objectWithKeyValues:dict];
                [self.matchListArray addObject:model];
                
            }
            
//            if (self.intergralListArray.count == 0) {
//                _intergralTag = -1;
//            }
            //杯赛阶段
            NSMutableArray * array = responseObject[@"KindList"];
            [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                KindListModel * model = [KindListModel mj_objectWithKeyValues:obj];
                [self.kindListArray addObject:model];
                
                if (model.IsCurrent) {
                    selectTag = idx;
//                    _kindId = model.KindId;
                    [self getTheCorrespondingData:idx];
                }
            }];
//            [self.tableView setTableHeaderView:[self tableHeadView]];
            _headerView.kindListArray = self.kindListArray;
        }
        
        [CommonClass endRefreshing:self.tableView];
        [self.tableView reloadData];
    }];
    
}

- (NSMutableArray *)extractionOfTheSameElementWithArray:(NSMutableArray *)modelArray{
    
    NSMutableArray *array = [NSMutableArray arrayWithArray:modelArray];
    MyLog(@"%ld",array.count);
    NSMutableArray *dateMutablearray = [@[] mutableCopy];
    
   
    
    for (int i = 0; i < array.count; i ++) {
        NSDictionary * dict = array[i];
        NSString *string = dict[@"Group"];
        NSMutableArray *tempArray = [@[] mutableCopy];
        //
        NSMutableDictionary * modelDict = @{}.mutableCopy;
        NSString *jstring = dict[@"Group"];
        [tempArray addObject:dict];
        [modelDict setObject:tempArray forKey:@"data"];
        [modelDict setObject:jstring forKey:@"Group"];
//        [dateMutablearray addObject:modelDict];
        for (int j = i+1; j < array.count; j ++) {
            NSDictionary * jsDict = array[j];
            NSString *jstring = jsDict[@"Group"];
            if([string isEqualToString:jstring]){
                [tempArray addObject:jsDict];
                [modelDict setObject:tempArray forKey:@"data"];
                [modelDict setObject:jstring forKey:@"Group"];
                [array removeObjectAtIndex:j];
                j -= 1;
            }
                
        }
        [dateMutablearray addObject:modelDict];
    }
    for (NSInteger i = 0; i<dateMutablearray.count; i++) {
        NSDictionary * dict = dateMutablearray[i];
        if ([dict[@"Group"] isEqualToString:@""]) {
            MatchListModel * model = [MatchListModel mj_objectWithKeyValues:dict];
            [self.nullMatchListArray addObject:model];
            [self.nullMatchListCopyArray addObject:model];
            [dateMutablearray removeObject:dict];
        }
    }
    self.nullMatchListCopyArray = self.nullMatchListArray.mutableCopy;
    return dateMutablearray;
//    MyLog(@"%@",dateMutablearray);
}


#pragma mark 🔥 Event
- (NSArray *)handelDictionary:(NSArray *)array{//按字母表排序
    NSMutableArray * sortArray = [[NSMutableArray alloc]init];
    for (id _obj in [array sortedArrayUsingSelector:@selector(compare:)]) {
        [sortArray addObject:_obj];
    }
    return sortArray;
}
- (void)clickStageButton:(UIButton *)sender{
//    [self.tableView reloadData];
    MyLog(@"tag -- %zd",sender.tag);
    selectTag = sender.tag-100;
    
//    KindListModel * KModel = self.kindListArray[selectTag-100];
    //选中变红色 其他按钮变为白色
    if (selectedBtn) {
        [selectedBtn setBackgroundImage:[UIImage imageNamed:@"StageButton"] forState:UIControlStateNormal];
        [selectedBtn setTitleColor:LSSubColor5D5D5D forState:UIControlStateNormal];
    }
    selectedBtn = sender;
    [selectedBtn setBackgroundImage:[UIImage imageNamed:@"StageButtonSelected"] forState:UIControlStateNormal];
    [selectedBtn setTitleColor:LSTitleWhiteColor forState:UIControlStateNormal];
//    _kindId = KModel.KindId;
//    [self loadData:YES];
    [self getTheCorrespondingData:selectTag];
    
}

- (void)getTheCorrespondingData:(NSInteger )idx{
     KindListModel * KModel = self.kindListArray[idx];
    [self.intergralListArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        LSCupIntegralModel * model = (LSCupIntegralModel *)obj;
        if ([model.KindId isEqualToString:KModel.KindId]) {
            _intergralTag = idx;
            //            _kindId = model.KindId;
            return ;
            
        }else{
            
            _intergralTag = -1;
        }
    }];
    self.nullMatchListArray = [[NSMutableArray alloc] initWithArray:self.nullMatchListCopyArray copyItems:YES];
    [self.nullMatchListArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        MatchListModel * model = (MatchListModel *)obj;
        NSMutableArray * array = @[].mutableCopy;
        [model.data enumerateObjectsUsingBlock:^(data * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            data * data = obj;
            if ([data.KindId isEqualToString:KModel.KindId]) {
                [array addObject:data];
            }
        }];
        model.data = array.mutableCopy;
        
    }];
    
    [self.tableView reloadData];
    
}

- (void)clickCheckMoreButton:(UIButton *)sender{
//    sender.selected = !sender.selected;
//    isOpen = sender.selected;
    isOpen = !isOpen;
    [_tableView beginUpdates];
    [self.tableView setTableHeaderView:[self tableHeadView]];
    [_tableView endUpdates];
    
}


-(UIView *)tableHeadView{
//    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LSScreenWidth, 32)];
//    view.backgroundColor = [UIColor whiteColor];
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = LSSubGrayColorf7;
    
    UILabel *stageLable = [[UILabel alloc] init];
    stageLable.text = @"杯赛阶段";
    stageLable.font = LSFontSize12;
    stageLable.textAlignment = NSTextAlignmentLeft;
    stageLable.textColor = RGB(51, 51, 51);
    [headerView addSubview:stageLable];
    stageLable.sd_layout
    .leftEqualToView(headerView).offset(LSAutoVlaue(15, LSScreenWidth))
    .topEqualToView(headerView).offset(LSAutoVlaue(11, LSScreenHeight))
    .widthIs(LSAutoVlaue(80, LSScreenWidth))
    .heightIs(LSAutoVlaue(12, LSScreenHeight));
    
    UILabel *nowLable = [[UILabel alloc] init];
    
    nowLable.font = LSFontSize12;
    nowLable.textAlignment = NSTextAlignmentRight;
    nowLable.textColor = RGB(51, 51, 51);
    
    [headerView addSubview:nowLable];
    nowLable.sd_layout
    .rightSpaceToView(headerView, 5)
    .centerYEqualToView(stageLable)
    .heightIs(LSAutoVlaue(12, LSScreenHeight));
    [nowLable setSingleLineAutoResizeWithMaxWidth:180];
    
    checkMoreBtn = [[UIButton alloc] init];
    [checkMoreBtn setTitle:@"展开更多" forState:UIControlStateNormal];
    checkMoreBtn.titleLabel.font = LSFontSize(12, LSScreenWidth);
    [checkMoreBtn setTitleColor:RGB(102, 102, 102) forState:UIControlStateNormal];
    [checkMoreBtn setImage:[UIImage imageNamed:@"PullDown"] forState:UIControlStateNormal];
    [checkMoreBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 20)];
    [checkMoreBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 40, 0, -40)];
    [checkMoreBtn addTarget:self action:@selector(clickCheckMoreButton:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:checkMoreBtn];
    
    
    if(!isOpen){
//        NSMutableArray *Arr = @[].mutableCopy;
        NSArray *titleArr;
        if (self.kindListArray.count > 4) {
            titleArr = [self.kindListArray subarrayWithRange:NSMakeRange(0, 4)];
        }else if (self.kindListArray.count>0 && self.kindListArray.count<=4){
            titleArr = self.kindListArray;
        }else{
            titleArr = @[];
        }
        
//        NSArray *titleArr = @[@"第一圈",@"第二圈",@"第三圈",@"附加赛"];
        headerView.frame = CGRectMake(0, 0, LSScreenWidth, 116);
        for (int i = 0; i < titleArr.count; i ++) {
            
            KindListModel * model = titleArr[i];
            NSInteger index = i % 4;
            NSInteger page = i / 4;
            
            UIButton *stageBtn = [[UIButton alloc] initWithFrame:CGRectMake(index * (Button_Width + Width_Space) + Start_X, page  * (Button_Height + Height_Space)+Start_Y, Button_Width, Button_Height)];
            stageBtn.tag = i+100;
            if (model.IsCurrent) {
                selectTag = i;
            }
            
            //默认选中第一个
            if (i == selectTag) {
                
                [stageBtn setBackgroundImage:[UIImage imageNamed:@"StageButtonSelected"] forState:UIControlStateNormal];
                [stageBtn setTitleColor:LSTitleWhiteColor forState:UIControlStateNormal];
                nowLable.text = [NSString stringWithFormat:@"目前进行 %@",model.KindName];
                selectedBtn=stageBtn;
            }else{
                
                [stageBtn setBackgroundImage:[UIImage imageNamed:@"StageButton"] forState:UIControlStateNormal];
                [stageBtn setTitleColor:LSSubColor5D5D5D forState:UIControlStateNormal];
            }
            [stageBtn setTitle:model.KindName forState:UIControlStateNormal];
            
            stageBtn.titleLabel.font = LSFontSize12;
            [stageBtn  addTarget:self action:@selector(clickStageButton:) forControlEvents:UIControlEventTouchUpInside];
            [headerView addSubview:stageBtn];
         
            
            checkMoreBtn.sd_layout
            .centerXEqualToView(headerView)
            .bottomEqualToView(headerView).offset(-LSAutoVlaue(10, LSScreenHeight))
            .widthIs(LSAutoVlaue(80, LSScreenWidth))
            .heightIs(LSAutoVlaue(30, LSScreenHeight));
        }
    }else{
//        NSArray *titleArr = @[@"第一圈",@"第二圈",@"第三圈",@"附加赛",@"分组赛",@"十六强",@"半准决赛",@"准决赛",@"决赛"];
        headerView.frame = CGRectMake(0, 0, LSScreenWidth, 226);
        for (int i = 0; i < self.kindListArray.count; i ++) {
            KindListModel * model = self.kindListArray[i];
            NSInteger index = i % 4;
            NSInteger page = i / 4;
            
            UIButton *stageBtn = [[UIButton alloc] initWithFrame:CGRectMake(index * (Button_Width + Width_Space) + Start_X, page  * (Button_Height + Height_Space)+Start_Y, Button_Width, Button_Height)];
            stageBtn.tag = i+100;
            //默认选中第一个
            if (i == selectTag) {
                [stageBtn setBackgroundImage:[UIImage imageNamed:@"StageButtonSelected"] forState:UIControlStateNormal];
                [stageBtn setTitleColor:LSTitleWhiteColor forState:UIControlStateNormal];
                nowLable.text = [NSString stringWithFormat:@"目前进行 %@",model.KindName];
                selectedBtn=stageBtn;
            }else{
                [stageBtn setBackgroundImage:[UIImage imageNamed:@"StageButton"] forState:UIControlStateNormal];
                [stageBtn setTitleColor:LSSubColor5D5D5D forState:UIControlStateNormal];
            }
            
            [stageBtn setTitle:model.KindName forState:UIControlStateNormal];
            stageBtn.titleLabel.font = LSFontSize12;
            [stageBtn  addTarget:self action:@selector(clickStageButton:) forControlEvents:UIControlEventTouchUpInside];
            [headerView addSubview:stageBtn];
            
            [checkMoreBtn setImage:[UIImage imageNamed:@"PullUp"] forState:UIControlStateNormal];
            checkMoreBtn.sd_layout
            .centerXEqualToView(headerView)
            .bottomEqualToView(headerView).offset(-LSAutoVlaue(40, LSScreenHeight))
            .widthIs(LSAutoVlaue(100, LSScreenWidth))
            .heightIs(LSAutoVlaue(30, LSScreenHeight));
            
            
        }
    }
    
    
    //    if (self.leagueType == 1) {
    return headerView;
    
}

#pragma mark 🔥 tableViewDelegate tableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (_intergralTag == -1) {
        MatchListModel * model = self.nullMatchListArray[section];
        return model.data.count;
//        return 1;
    }else{
        LSCupIntegralModel * model = self.intergralListArray[_intergralTag];
        GroupList * group = model.GroupList[section];
        if (group.isSelected == YES) {
            MatchListModel * model = self.matchListArray[section];
            return model.data.count;
        }
        return group.subIntergralList.count;
    }
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (_intergralTag == -1) {
        return self.nullMatchListArray.count;
    }else{
        if (self.intergralListArray.count == 0) {
            return 0;
        }
        LSCupIntegralModel * model = self.intergralListArray[_intergralTag];
        return model.GroupList.count;
    }
   
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_intergralTag == -1) {
        MatchListModel * matchModel = self.nullMatchListArray[indexPath.section];
        LSCupScheduleCell * cell = [LSCupScheduleCell cupScheduleCellByTableView:tableView];
        cell.model = matchModel.data[indexPath.row];
        return cell;
    }else{
        LSCupIntegralModel * model = self.intergralListArray[_intergralTag];
        GroupList * group = model.GroupList[indexPath.section];
        MatchListModel * matchModel = self.matchListArray[indexPath.section];
        if (group.isSelected == YES ) {
            
            LSCupScheduleCell * cell = [LSCupScheduleCell cupScheduleCellByTableView:tableView];
            cell.model = matchModel.data[indexPath.row];
            return cell;
        }else{
            LSCupIntergralCell *fixturesCell = [LSCupIntergralCell cupIntergralCellByTableView:tableView];
            subIntergralList * model = group.subIntergralList[indexPath.row];
            [fixturesCell configDataWithModel:model withIndexRow:indexPath.row with:self.imageArray];
            return fixturesCell;
        }
    }
    
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 35;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (_intergralTag == -1) {
        return [UIView new];
    }
    LSCupIntegralHeaderView * headerView = [[LSCupIntegralHeaderView alloc] initWithReuseIdentifier:@"HeaderView"];
    LSCupIntegralModel * model = self.intergralListArray[_intergralTag];
    GroupList * group = model.GroupList[section];
    headerView.model = model.GroupList[section];
    KWeakSelf(self);
    headerView.block = ^(UIButton *sender) {
        _selectSection = section;
        sender.selected = !sender.selected;
        if (sender.selected) {
            group.isSelected = YES;
            sender.backgroundColor = RGB(229,115,94);
            sender.titleLabel.textColor = LSTitleWhiteColor;
        }else{
            sender.backgroundColor = LSTitleWhiteColor;
            sender.titleLabel.textColor = RGB(93,93,93);
            group.isSelected = NO;
        }
        [weakself.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationFade];
            
        };
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (_intergralTag == -1) {
        return 0.01;
    }else{
        LSCupIntegralModel * model = self.intergralListArray[_intergralTag];
        GroupList * group = model.GroupList[section];
        if (group.isSelected) {
            return LSScareValue(30, LSScreenWidth);
        }
        
        return LSScareValue(60, LSScreenWidth);
    }
    
}

#pragma mark 🔥 Getter
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, LSScreenWidth, LSScreenHeight-35-LSNavBarHeight) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.sectionHeaderHeight = 0;
        _tableView.sectionFooterHeight = 0;
        _tableView.backgroundColor =LSBackGroundColor;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

@end

